package controller

import (
	"beergo/lib/tool"
	"encoding/json"
	"strings"
)

type ListQuery struct {
	Conditions map[string]interface{} `json:"_where"`
	Order      []string               `json:"_order"`
	Limit      int                    `json:"limit"`
	Page       int                    `json:"page"`
	Total      int                    `json:"total"`
	Depth      int                    `json:"_depth"`
	Group      string                 `json:"_g"`
}

func (this ListQuery) CreateFilter() map[string]interface{} {
	conditions := tool.StringKeyMap{}
	for k, item := range this.Conditions {
		if item != "" {
			if strings.HasSuffix(k, "__like") {
				k = strings.ReplaceAll(k, "__like", "__icontains")
			}
			if strings.HasSuffix(k, "__sw") {
				k = strings.ReplaceAll(k, "__sw", "__startswith")
			}
			if strings.HasSuffix(k, "__ew") {
				k = strings.ReplaceAll(k, "__ew", "__endswith")
			}
			if strings.HasSuffix(k, "__eq") {
				k = strings.ReplaceAll(k, "__eq", "__iexact")
			}
			conditions[k] = item
		}
	}
	return conditions
}

func (this ListQuery) CreateOrder() []string {
	return this.Order
}

func (this ListQuery) CreateOrderOne() string {
	if len(this.Order) == 0 {
		return ""
	} else {
		return this.Order[0]
	}
}

func (this ListQuery) CreateLimit() int {
	return this.Limit
}

func (this ListQuery) CreateOffset() int {
	offset := this.Page*this.Limit - this.Limit
	if offset < 0 {
		offset = 0
	}
	return offset
}

func (this ListQuery) CreateGroup() string {
	if this.Group == "" {
		return "app"
	}
	return this.Group
}

func (this ListQuery) CreateDepth() int {
	if this.Depth == 0 {
		return 1
	}
	return this.Depth
}

func (this ListQuery) Get() []interface{} {
	re := []interface{}{this.Conditions, this.Order, this.Limit, this.Page, this.Total}
	return re
}

func (this ListQuery) ToString() string {
	buf, _ := json.Marshal(this)
	return string(buf)
}

func (this ListQuery) CreateOrderFromJsonString(orderJson string) []string {
	data := strings.Fields(orderJson)
	order := []string{}
	for _, datum := range data {
		if datum != "" {
			order = append(order, datum)
		}
	}
	return order
}
func (this ListQuery) CreateFilterFromJsonString(orderJson string) map[string]interface{} {
	data := [][]string{}
	json.Unmarshal([]byte(orderJson), &data)
	where := map[string]interface{}{}
	for _, datum := range data {
		item := datum
		if len(item) != 3 {
			continue
		}
		if len(item[0]) == 0 {
			continue
		}
		where[item[0]+"__"+item[1]] = item[2]
	}

	return where
}
